#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from rbac import models
from rbac.forms.Role import RoleModelForm
from Arc.utils.GetData import getpage


def role_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    role_queryset = models.Role.objects.all()
    pager, data_list = getpage(request, role_queryset)
    return render(request, 'rbac/role_list.html', {'roles': data_list, 'pager': pager})


def role_add(request):
    """
    添加角色
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RoleModelForm()
        return render(request, 'rbac/form_temp.html', {'forms': form, })

    form = RoleModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:roles'))

    return render(request, 'rbac/form_temp.html', {'forms': form, })


def role_edit(request, pk):
    """
    编辑角色
    :param request:
    :param pk: 要修改的角色ID
    :return:
    """
    obj = models.Role.objects.filter(id=pk).first()
    print(obj)
    if not obj:
        return render(request, '404.html', {'error': '查看的角色不存在！'})
    if request.method == 'GET':
        form = RoleModelForm(instance=obj)
        return render(request, 'rbac/form_temp.html', {'forms': form})

    form = RoleModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:roles'))

    return render(request, 'rbac/form_temp.html', {'forms': form})


def role_del(request, pk):
    """
    删除角色
    :param request:
    :param pk:
    :return:
    """
    if request.method == 'POST':
        if pk == request.POST.get('pk') and request.POST.get('csrfmiddlewaretoken'):
            models.Role.objects.filter(id=pk).delete()
            return HttpResponse('200')
    else:
        return render(request, '403.html')

    #
